package com.example.qrcode.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.qrcode.entity.ProductDetail;
import com.example.qrcode.service.ProductDetailService;
import com.example.qrcode.vo.ResultVo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/productDetail")
public class ProductDetailController {

    @Resource
    private ProductDetailService productDetailService;

    @GetMapping("/test")
    public ResultVo<String> test() {
        return ResultVo.success("测试接口  productDetail");
    }


    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody ProductDetail productDetail) {
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("=== 保存产品信息 ===");
            System.out.println("产品序列号: " + productDetail.getProductSNo());
            System.out.println("设备标识: " + productDetail.getDeviceId());
            System.out.println("出线数量: " + productDetail.getLineNum());
            System.out.println("出线数量类型: " + (productDetail.getLineNum() != null ? productDetail.getLineNum().getClass().getName() : "null"));
            System.out.println("图片1 URL: " + productDetail.getImage1Url());
            System.out.println("图片2 URL: " + productDetail.getImage2Url());

            if (productDetail.getProductSNo() == null || productDetail.getProductSNo().isEmpty()) {
                result.put("code", 1);
                result.put("msg", "产品序列号不能为空");
                return result;
            }

            // 新增：验证设备ID是否存在于二维码管理系统中
            boolean deviceExists = productDetailService.checkDeviceExists(productDetail.getProductSNo());
            if (!deviceExists) {
                result.put("code", 1);
                result.put("msg", "设备ID不存在，请检查后重试");
                return result;
            }

            // 检查是否存在该产品
            ProductDetail existingProduct = productDetailService.getByProductSNo(productDetail.getProductSNo());

            boolean saveResult;
            if (existingProduct != null) {
                // 部分更新：只更新非空字段
                System.out.println("更新现有产品信息");

                // 只更新传入的非空字段
                if (productDetail.getImage1Url() != null) {
                    existingProduct.setImage1Url(productDetail.getImage1Url());
                    System.out.println("更新图片1 URL: " + productDetail.getImage1Url());
                }
                if (productDetail.getImage2Url() != null) {
                    existingProduct.setImage2Url(productDetail.getImage2Url());
                    System.out.println("更新图片2 URL: " + productDetail.getImage2Url());
                }

                // 更新其他字段（如果传入了的话）
                updateProductFields(existingProduct, productDetail);

                saveResult = productDetailService.updateById(existingProduct);
                System.out.println("更新结果: " + saveResult);
            } else {
                // 新增产品信息
                System.out.println("新增产品信息");
                saveResult = productDetailService.save(productDetail);
                System.out.println("新增结果: " + saveResult);
            }

            if (saveResult) {
                // 新增：获取二维码管理系统中的deviceId
                String deviceId = productDetailService.getDeviceIdFromQRSystem(productDetail.getProductSNo());
                
                // 验证保存后的数据
                ProductDetail savedProduct = productDetailService.getByProductSNo(productDetail.getProductSNo());
                if (savedProduct != null) {
                    System.out.println("=== 保存后的数据验证 ===");
                    System.out.println("保存后的出线数量: " + savedProduct.getLineNum());
                    System.out.println("保存后的设备标识: " + savedProduct.getDeviceId());
                }
                
                result.put("code", 0);
                result.put("msg", "保存成功");
                result.put("deviceId", deviceId); // 返回deviceId
                System.out.println("返回的deviceId: " + deviceId);
            } else {
                result.put("code", 1);
                result.put("msg", "保存失败");
            }
        } catch (Exception e) {
            System.err.println("保存异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "保存异常：" + e.getMessage());
        }
        return result;
    }

    // 更新产品字段的辅助方法
    private void updateProductFields(ProductDetail existing, ProductDetail updated) {
        // 基本信息
        if (updated.getUserId() != null) existing.setUserId(updated.getUserId());
        if (updated.getDeviceId() != null) existing.setDeviceId(updated.getDeviceId());
        if (updated.getCommunicationMode() != null) existing.setCommunicationMode(updated.getCommunicationMode());
        if (updated.getClientId() != null) existing.setClientId(updated.getClientId());
        if (updated.getUsername() != null) existing.setUsername(updated.getUsername());
        if (updated.getPassword() != null) existing.setPassword(updated.getPassword());
        if (updated.getInstallationLocation() != null) existing.setInstallationLocation(updated.getInstallationLocation());
        if (updated.getApplicationScenario() != null) existing.setApplicationScenario(updated.getApplicationScenario());

        // 出线数量
        if (updated.getLineNum() != null) {
            System.out.println("更新出线数量: " + updated.getLineNum() + " -> " + existing.getLineNum());
            existing.setLineNum(updated.getLineNum());
            System.out.println("更新后出线数量: " + existing.getLineNum());
        } else {
            System.out.println("出线数量为null，不更新");
        }

        // 变压器信息
        if (updated.getLine10kvName() != null) existing.setLine10kvName(updated.getLine10kvName());
        if (updated.getTransformerName() != null) existing.setTransformerName(updated.getTransformerName());
        if (updated.getTransformerRatedCapacity() != null) existing.setTransformerRatedCapacity(updated.getTransformerRatedCapacity());
        if (updated.getTransformerRatio() != null) existing.setTransformerRatio(updated.getTransformerRatio());

        // 线路信息 - 支持8个线路
        if (updated.getLine1Name() != null) existing.setLine1Name(updated.getLine1Name());
        if (updated.getLine1RatedCapacity() != null) existing.setLine1RatedCapacity(updated.getLine1RatedCapacity());
        if (updated.getLine1Ratio() != null) existing.setLine1Ratio(updated.getLine1Ratio());
        
        if (updated.getLine2Name() != null) existing.setLine2Name(updated.getLine2Name());
        if (updated.getLine2RatedCapacity() != null) existing.setLine2RatedCapacity(updated.getLine2RatedCapacity());
        if (updated.getLine2Ratio() != null) existing.setLine2Ratio(updated.getLine2Ratio());
        
        if (updated.getLine3Name() != null) existing.setLine3Name(updated.getLine3Name());
        if (updated.getLine3RatedCapacity() != null) existing.setLine3RatedCapacity(updated.getLine3RatedCapacity());
        if (updated.getLine3Ratio() != null) existing.setLine3Ratio(updated.getLine3Ratio());
        
        if (updated.getLine4Name() != null) existing.setLine4Name(updated.getLine4Name());
        if (updated.getLine4RatedCapacity() != null) existing.setLine4RatedCapacity(updated.getLine4RatedCapacity());
        if (updated.getLine4Ratio() != null) existing.setLine4Ratio(updated.getLine4Ratio());
        
        if (updated.getLine5Name() != null) existing.setLine5Name(updated.getLine5Name());
        if (updated.getLine5RatedCapacity() != null) existing.setLine5RatedCapacity(updated.getLine5RatedCapacity());
        if (updated.getLine5Ratio() != null) existing.setLine5Ratio(updated.getLine5Ratio());
        
        if (updated.getLine6Name() != null) existing.setLine6Name(updated.getLine6Name());
        if (updated.getLine6RatedCapacity() != null) existing.setLine6RatedCapacity(updated.getLine6RatedCapacity());
        if (updated.getLine6Ratio() != null) existing.setLine6Ratio(updated.getLine6Ratio());
        
        if (updated.getLine7Name() != null) existing.setLine7Name(updated.getLine7Name());
        if (updated.getLine7RatedCapacity() != null) existing.setLine7RatedCapacity(updated.getLine7RatedCapacity());
        if (updated.getLine7Ratio() != null) existing.setLine7Ratio(updated.getLine7Ratio());
        
        if (updated.getLine8Name() != null) existing.setLine8Name(updated.getLine8Name());
        if (updated.getLine8RatedCapacity() != null) existing.setLine8RatedCapacity(updated.getLine8RatedCapacity());
        if (updated.getLine8Ratio() != null) existing.setLine8Ratio(updated.getLine8Ratio());

        System.out.println("完成字段更新，出线数量: " + existing.getLineNum());
    }





    @GetMapping("/getByProductSNo/{productSNo}")
    public ResultVo<ProductDetail> getByProductSNo(@PathVariable String productSNo) {
        System.out.println("=== 获取产品详情 ===");
        System.out.println("请求产品序列号: " + productSNo);

        try {
            if (productSNo == null || productSNo.isEmpty()) {
                return ResultVo.error("产品序列号不能为空");
            }

            ProductDetail productDetail = productDetailService.getByProductSNo(productSNo);
            System.out.println("数据库查询结果: " + productDetail);

            if (productDetail != null) {
                System.out.println("产品序列号: " + productDetail.getProductSNo());
                System.out.println("设备标识: " + productDetail.getDeviceId());
                System.out.println("出线数量: " + productDetail.getLineNum());
                System.out.println("图片1 URL: " + productDetail.getImage1Url());
                System.out.println("图片2 URL: " + productDetail.getImage2Url());
                
                // 新增：主接线图展示时的出线数量判断和日志打印
                if (productDetail.getLineNum() != null) {
                    System.out.println("=== 主接线图出线数量判断 ===");
                    System.out.println("设备ID: " + productDetail.getProductSNo());
                    System.out.println("出线数量: " + productDetail.getLineNum() + "路");
                    System.out.println("设备类型: " + (productDetail.getLineNum() <= 4 ? "小型设备" : "大型设备"));
                    System.out.println("需要显示" + productDetail.getLineNum() + "个出线配置");
                } else {
                    System.out.println("警告：设备出线数量未设置");
                }
                
                return ResultVo.success(productDetail);
            } else {
                System.out.println("产品不存在");
                return ResultVo.error("产品不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("获取产品详情失败: " + e.getMessage());
            return ResultVo.error("获取产品详情失败：" + e.getMessage());
        }
    }

    // 新增：设备ID验证接口
    @GetMapping("/checkDevice/{productSNo}")
    public ResultVo<Boolean> checkDevice(@PathVariable String productSNo) {
        System.out.println("=== 验证设备ID ===");
        System.out.println("请求验证的设备ID: " + productSNo);
        
        try {
            if (productSNo == null || productSNo.isEmpty()) {
                return ResultVo.error("设备ID不能为空");
            }
            
            boolean exists = productDetailService.checkDeviceExists(productSNo);
            System.out.println("设备ID验证结果: " + exists);
            
            if (exists) {
                return ResultVo.success(true);
            } else {
                return ResultVo.error("设备ID不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("设备ID验证失败: " + e.getMessage());
            return ResultVo.error("设备ID验证失败：" + e.getMessage());
        }
    }

    // 在 ProductDetailController 中添加
    @PostMapping("/updateImageUrl")
    public ResultVo<String> updateImageUrl(@RequestBody Map<String, Object> requestData) {
        try {
            String productSNo = (String) requestData.get("productSNo");
            String imageUrl = (String) requestData.get("imageUrl");
            String imageType = (String) requestData.get("imageType");
            
            if (productSNo == null || productSNo.isEmpty()) {
                return ResultVo.error("产品序列号不能为空");
            }
            
            if (imageUrl == null || imageUrl.isEmpty()) {
                return ResultVo.error("图片URL不能为空");
            }
            
            if (imageType == null || imageType.isEmpty()) {
                return ResultVo.error("图片类型不能为空");
            }
            
            ProductDetail productDetail = productDetailService.getByProductSNo(productSNo);
            if (productDetail == null) {
                return ResultVo.error("产品不存在");
            }
            
            // 根据图片类型更新对应的字段
            if ("image1".equals(imageType)) {
                productDetail.setImage1Url(imageUrl);
            } else if ("image2".equals(imageType)) {
                productDetail.setImage2Url(imageUrl);
            } else {
                return ResultVo.error("不支持的图片类型");
            }
            
            boolean updateResult = productDetailService.updateById(productDetail);
            if (updateResult) {
                return ResultVo.success("图片URL更新成功");
            } else {
                return ResultVo.error("图片URL更新失败");
            }
            
        } catch (Exception e) {
            System.err.println("更新图片URL异常: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error("更新图片URL失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据产品序列号删除产品详情
     * @param productSNo 产品序列号
     * @return 删除结果
     */
    @DeleteMapping("/deleteByProductSNo/{productSNo}")
    public ResultVo<String> deleteByProductSNo(@PathVariable String productSNo) {
        try {
            System.out.println("=== 删除产品详情 ===");
            System.out.println("产品序列号: " + productSNo);
            
            if (productSNo == null || productSNo.isEmpty()) {
                return ResultVo.error("产品序列号不能为空");
            }
            
            // 检查产品是否存在
            ProductDetail existingProduct = productDetailService.getByProductSNo(productSNo);
            if (existingProduct == null) {
                return ResultVo.error("产品不存在");
            }
            
            // 执行删除操作 - 使用产品序列号删除
            boolean deleteResult = productDetailService.removeByProductSNo(productSNo);
            
            if (deleteResult) {
                System.out.println("产品删除成功: " + productSNo);
                return ResultVo.success("产品删除成功");
            } else {
                System.out.println("产品删除失败: " + productSNo);
                return ResultVo.error("产品删除失败");
            }
            
        } catch (Exception e) {
            System.err.println("删除产品详情异常: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error("删除产品详情失败: " + e.getMessage());
        }
    }
}